package brinaryTree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class N257_BinaryTreePaths {
    public List<String> binaryTreePaths_Iter(TreeNode root) {
        Stack<Object> stack = new Stack<>();
        List<String> result = new ArrayList<>();
        if (root == null) return result;
        stack.push(root);
        stack.push(root.val + "");
        while (!stack.isEmpty()) {
            String path = (String) stack.pop();
            TreeNode node = (TreeNode) stack.pop();

            if (node.left == null && node.right == null) {
                result.add(path);
            }

            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }

            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
        }
        return result;
    }

    public List<String> binaryTreePaths(TreeNode root) {
        List<Integer> paths = new ArrayList<>();
        List<String> result = new ArrayList<>();
        if (root == null) return result;
        traversal(root, paths, result);
        return result;
    }

    private void traversal(TreeNode node, List<Integer> paths, List<String> result) {
        paths.add(node.val);
        // 左右子节点都为空，即叶子节点
        if (node.left == null && node.right == null) {
            StringBuilder sb = new StringBuilder();
            // 添加路径到result中
            for (int i = 0; i < paths.size() - 1; i++) {
                sb.append(paths.get(i)).append("->");
            }
            sb.append(paths.get(paths.size() - 1));
            result.add(sb.toString());
            return;
        }
        // 有左子节点
        if (node.left != null) {
            traversal(node.left, paths, result);
            paths.remove(paths.size() - 1);
        }
        // 有右节点
        if (node.right != null) {
            traversal(node.right, paths, result);
            paths.remove(paths.size() - 1);
        }
    }


}
